package com.cskaoyan.mall.pay.service.impl;

import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.mall.commons.result.ServiceCallResponse;
import com.cskaoyan.mall.pay.constants.PayResult;
import com.cskaoyan.mall.pay.constants.PayRetCode;
import com.cskaoyan.mall.pay.dal.entitys.Payment;
import com.cskaoyan.mall.pay.dal.persistence.PaymentMapper;
import com.cskaoyan.mall.pay.form.PaymentRequest;
import com.cskaoyan.mall.pay.remote.OrderApiClient;
import com.cskaoyan.mall.pay.service.PayCoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;

@Service
public class PayCoreServiceImpl implements PayCoreService {


    @Autowired
    PayHelper helper;

    @Autowired
    PaymentMapper paymentMapper;

    @Autowired
    OrderApiClient orderApiClient;

    @Override
    public String aliPay(PaymentRequest request) {

        // 1. 请支付宝，携带订单参数，获取支付二维码
        String qrCode = helper.test_trade_precreate(request);
        // 2. 判断获取结果
        if (qrCode == null) {
           throw new BizException(PayRetCode.GET_CODE_FALIED.getCode(),
                   PayRetCode.GET_CODE_FALIED.getMsg());
        }

        //3. 获取支付二维码成功，在tb_payment插入一条记录，订单的支付信息( TRADE_PROCESSING)
        Payment payment = new Payment();
        payment.setStatus(PayResult.TRADE_PROCESSING.getCode());
        payment.setOrderId(request.getOrderId());
        payment.setProductName(request.getInfo());
        payment.setPayerUid(request.getUserId());
        payment.setPayerName(request.getNickName());
        payment.setPayerAmount(request.getMoney());
        payment.setOrderAmount(request.getMoney());
        payment.setPayWay(request.getPayType());
        payment.setCreateTime(new Date());
        payment.setUpdateTime(new Date());
        paymentMapper.insertSelective(payment);
        return qrCode;
    }

    @Override
    public boolean queryAlipayRet(String orderId) {
        boolean success = helper.test_trade_query(orderId);
        if (success) {
            /*
                   支付成功
                   1. 修改tb_payment表中，针对订单的支付状态，TRADE_SUCCESS

                   // 这里支付服务 ——> 订单服务
                   2. 修改订单状态为已支付
                   3. 根据订单id，查询订单中包含的所有订单商品，根据其下单的数量，扣减
                      对应商品的锁定库存
              */
            Payment payment = new Payment();
            payment.setUpdateTime(new Date());
            payment.setStatus(PayResult.TRADE_SUCCESS.getCode());
            Example example = new Example(Payment.class);
            example.createCriteria().andEqualTo("orderId",orderId);
            paymentMapper.updateByExampleSelective(payment,example);

            // 修改 订单及其相关表
            ServiceCallResponse serviceCallResponse = orderApiClient.payOrderSuccess(orderId);
            return true;


        } else {
            /*
                  支付失败：
                  如果支付失败，tb_payment表中，针对订单的支付状态，TRADE_FAILURE
             */
            Payment payment = new Payment();
            payment.setUpdateTime(new Date());
            payment.setStatus(PayResult.TRADE_FAILURE.getCode());
            Example example = new Example(Payment.class);
            example.createCriteria().andEqualTo("orderId",orderId);
            paymentMapper.updateByExampleSelective(payment,example);
        }
        return false;
    }
}
